package com.tvunetworks.center.user.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tvunetworks.center.common.util.JsonUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: tvucc-aggregator
 * @description: InstanceApiUtil
 * @author lebronchen
 * @create: 2020-04-23 14:00
 **/
@Slf4j
public class JwtUtil {
    static char []   HEXDIGITS= { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    /**
     * MAPPER
     */
    public static final ObjectMapper MAPPER = new ObjectMapper();
    /**
     * 解密
     *
     * @param jsonWebToken jsonWebToken
     * @param base64Security base64Security
     * @return Claims
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(base64Security.getBytes("UTF-8"))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            log.error(ex.toString(), ex);
            return null;
        }
    }
    /**
     * 前三个参数为自己用户token的一些信息比如id，权限，名称等。不要将隐私信息放入（大家都可以获取到）
     *
     * @param map map
     * @param base64Security base64Security
     * @return String
     */
    public static String createJWT(Map<String, Object> map, String base64Security) {
        try {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
            //添加构成JWT的参数
            String json = null;
            try {
                json = MAPPER.writeValueAsString(map);
            } catch (IOException e) {
                log.error(e.toString(), e);
            }
            JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                    .setPayload(json)
    //                .setPayload(new Gson().toJson(map))
                    .signWith(signatureAlgorithm, base64Security.getBytes("UTF-8")); //估计是第三段密钥
            //生成JWT
            return builder.compact();
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
         return null;
    }

    /**
     *
     * @param args args
     * @throws IOException 编译异常
     */
    public static void main(String[] args) throws IOException {
//        String jsonWebToken = "LTAIhgQHCh61aaPW";
//        String base64Security = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBrZXkiOiJlSUwwc3prNnRhdG1SSDd2QXRyZlhDdUJyMFhEUUQiLCJ0aW1lc3RhbXAiOjE1NjE1NDM4MjQyODR9.2i_iIDZ7sm7UAMeApzu3EShqX43mcCSpnjYrVvGtz90";
//
//        Claims claims = parseJWT(base64Security, jsonWebToken);
//        System.out.println(claims);
        String key = "8a8c96f95b19ca27015b19ddca0e0013";
        long timestamp = System.currentTimeMillis();
        String requestKey = MD5(timestamp + key);
        Map<String, Object> map = new HashMap<>();
        map.put("key", "dwdwd");
        map.put("value", "vavava");
        String jwt = createJWT(map, requestKey);
        System.out.println(jwt);
        Claims claims = parseJWT(jwt, requestKey);
        String result = JsonUtil.toJsonStr(claims);
        System.out.println("服务端返回值解密：" + result);
    }

    /**
     *
     * @param string string
     * @return String
     */
    public static String MD5(String string) {
        return encrypt(string, "MD5").toLowerCase();
    }
    private static String encrypt(String str, String type) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(type);
            messageDigest.update(str.getBytes("UTF-8"));
            byte[] digest = messageDigest.digest();
            return getFormattedText(digest).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.toString(), e);
            return null;
        } catch (UnsupportedEncodingException e) {
            log.error(e.toString(), e);
            return null;
        }
    }
    private static String getFormattedText(byte[] bytes) {
        final StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (int j = 0; j < bytes.length; j++) {
            buf.append(HEXDIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEXDIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


}
